package com.system.runtai.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.system.runtai.entity.*;
import com.system.runtai.service.AppletUserService;
import com.system.runtai.service.IpaEnterService;
import com.system.runtai.service.PostedService;
import com.system.runtai.utils.*;
import com.system.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 微信程序用户 前端控制器
 * </p>
 *
 * @author runtai
 * @since 2024-03-29
 */
@Api(tags = "微信程序用户")
@RestController
@RequestMapping("/runtai/applet-user")
public class AppletUserController {

    @Autowired
    private AppletUserService appletUserService;

    //    @Autowired
//    private AppletVO applet;
    @Autowired
    private HttpClients httpClientUtil;

    @Autowired
    private PostedService postedService;

    @Autowired
    private WXPhoneLogin wxPhoneLogin;

    @Autowired
    private IpaEnterService ipaEnterService;


    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody AppletUser user, HttpSession httpSession) {
        //获取手机号
        String phone = user.getPhone();

        if (!StringUtils.isEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            SMSUtils.sendMessage("润泰救援科技","SMS_300561066",phone,code);

            httpSession.setAttribute(phone, code);
            return Result.ok(code).message("手机短信验证码发送成功");
        }
        return Result.fail("手机短信验证码发送失败");
    }

    @PostMapping("/phonelogin")
    public Result login(@RequestBody Map user, HttpSession httpSession, @RequestBody LoginDto loginDto) {
        //获取当前手机号码
        String phone = user.get("phone").toString();
        //获取当前的验证码
        String code = user.get("code").toString();

        //获取在存在session中code
        Object codeSession = httpSession.getAttribute(phone);
        Object object = httpSession.getAttribute(code);

        //验证码进行校验
        if (object.equals(code) && object != null) {

//            //如果用户是第一次登陆就进行注册
//            LambdaQueryWrapper<AppletUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            userLambdaQueryWrapper.eq(AppletUser::getPhone,phone);
//
//            AppletUser userOne = appletUserService.getOne(userLambdaQueryWrapper);
//
//            //第一次登陆
//            if (userOne == null) {
//                userOne = new AppletUser();
//                //随机生成姓名进行存放
//                String randomChineseChar = ChineseUtil.getRandomChineseName();
//                userOne.setName(randomChineseChar);
//                userOne.setPhone(phone);
//                userOne.setStatus(1);
//                appletUserService.save(userOne);
//            }
//
//            //如果是第一次创建没有id，则需要通过手机号再次查询一次用户获取id,存放在session中
//            userOne = appletUserService.getOne(userLambdaQueryWrapper);
//
//            httpSession.setAttribute("user",userOne.getId());
//            BaseContext.setCurrentId(userOne.getId());
//            return Result.ok(userOne);


            //判断客户端传的code是否为空
            if (loginDto.getCode() == null) {
                return Result.fail().message("code不能为空");
            }

            LoginDto loginDto1 = wxPhoneLogin.appWxLogin(loginDto.getCode());
            QueryWrapper<AppletUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid", loginDto1.getOpenid());
            AppletUser appletUser1 = appletUserService.getOne(queryWrapper);
            if (appletUser1 == null) {
                //添加用户信息
//            appletUser.setHeadPortraits(appletUser.getHeadPortraits());
//            UUID uuid = UUID.randomUUID();
                //生成4个随机汉字
                AppletUser appletUser = new AppletUser();
                String randomCharacters = AppletUserController.getRandomCharacters(6);
                appletUser.setNickName(randomCharacters);
                System.out.println("生成名称 = " + randomCharacters);
                appletUser.setOpenid(loginDto1.getOpenid());
                appletUser.setCreateTime(LocalDateTime.now());
                appletUser.setPhone(phone);
                boolean save = appletUserService.save(appletUser);

                IpaEnter ipaEnter = new IpaEnter();
                ipaEnter.setAppletUserId(appletUser.getId());
                ipaEnter.setStart(2);
                ipaEnter.setCreateTime(LocalDateTime.now());
                AppletUser byId1 = appletUserService.getById(appletUser.getId());
                ipaEnter.setAvatar(byId1.getAvatar());
                ipaEnterService.save(ipaEnter);


                Map<String, Object> cliams = new HashMap<>();
                cliams.put("id", appletUser.getId());
                String token = JwtUtils.generateJwt(cliams);
                return Result.ok(token).message("登陆成功");
            } else {
                //更新用户信息
                appletUser1.setUpdateTime(LocalDateTime.now());//
                appletUserService.updateById(appletUser1);
                //生成token
                Map<String, Object> cliams = new HashMap<>();
                cliams.put("id", appletUser1.getId());
                String token = JwtUtils.generateJwt(cliams);

//                LambdaQueryWrapper<IpaEnter> wrapper = new LambdaQueryWrapper<>();
//                wrapper.eq(IpaEnter::getAppletUserId,appletUser1.getId());
//
//                IpaEnter one = ipaEnterService.getOne(wrapper);
//                if (one==null){
//                    IpaEnter ipaEnter = new IpaEnter();
//                    ipaEnter.setAppletUserId(appletUser1.getId());
//                    ipaEnterService.save(ipaEnter);
//                }


                LambdaQueryWrapper<AppletUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userLambdaQueryWrapper.eq(AppletUser::getPhone, phone);

                AppletUser userOne = appletUserService.getOne(userLambdaQueryWrapper);
                //如果是第一次创建没有id，则需要通过手机号再次查询一次用户获取id,存放在session中
                userOne = appletUserService.getOne(userLambdaQueryWrapper);

                httpSession.setAttribute("user", userOne.getId());

                return Result.ok(token).message("登录成功");
            }

        }

        return Result.fail("验证码错误,请重新输入").code(203);
    }


    /**
     * 退出登陆
     *
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> loginOut(HttpSession session) {
        session.removeAttribute("user");
        return Result.ok("退出成功");
    }


    @ApiOperation("获取头像和昵称")
    @PostMapping("/getHeadAndName")
    public Result getHeadAndName(@RequestBody LoginDto loginDto) {
        //判断客户端传的code是否为空
        if (loginDto.getCode() == null) {
            return Result.fail().message("code不能为空");
        }

        LoginDto loginDto1 = wxPhoneLogin.appWxLogin(loginDto.getCode());
        QueryWrapper<AppletUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", loginDto1.getOpenid());
        AppletUser appletUser1 = appletUserService.getOne(queryWrapper);
        if (appletUser1 == null) {
            //添加用户信息
//            appletUser.setHeadPortraits(appletUser.getHeadPortraits());
//            UUID uuid = UUID.randomUUID();
            //生成4个随机汉字
            AppletUser appletUser = new AppletUser();
            String randomCharacters = AppletUserController.getRandomCharacters(6);
            appletUser.setNickName(randomCharacters);
            System.out.println("生成名称 = " + randomCharacters);
            appletUser.setOpenid(loginDto1.getOpenid());
            appletUser.setCreateTime(LocalDateTime.now());
            boolean save = appletUserService.save(appletUser);

            IpaEnter ipaEnter = new IpaEnter();
            ipaEnter.setAppletUserId(appletUser.getId());
            ipaEnter.setCreateTime(LocalDateTime.now());
            ipaEnterService.save(ipaEnter);


            Map<String, Object> cliams = new HashMap<>();
            cliams.put("id", appletUser.getId());
            String token = JwtUtils.generateJwt(cliams);
            return Result.ok(token).message("登陆成功");
        } else {
            //更新用户信息
            appletUser1.setUpdateTime(LocalDateTime.now());//
            appletUserService.updateById(appletUser1);
            //生成token
            Map<String, Object> cliams = new HashMap<>();
            cliams.put("id", appletUser1.getId());
            String token = JwtUtils.generateJwt(cliams);
            return Result.ok(token).message("登录成功");
        }
    }


    public static String getRandomCharacters(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }


    @ApiOperation(value = "查询所有小程序用户")
    @GetMapping("/getList/AppleUserList")
    public Result<IPage<AppletUser>> appleUserList(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer limit, @RequestParam(required = false) String phone) {

        if (StringUtils.isEmpty(phone)) {
            Page<AppletUser> recommendPage = new Page<>(page, limit);
            IPage<AppletUser> iPage = appletUserService.page(recommendPage);
            return Result.ok(iPage);
        } else if (!StringUtils.isEmpty(phone)) {
            Page<AppletUser> recommendPage = new Page<>(page, limit);
            LambdaQueryWrapper<AppletUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(AppletUser::getPhone, phone);
            IPage<AppletUser> iPage = appletUserService.page(recommendPage);
            return Result.ok(iPage);
        }
        Page<AppletUser> recommendPage = new Page<>(page, limit);
        IPage<AppletUser> iPage = null;
        return Result.fail(iPage).message("暂无数据！！！");
    }


    //TODO 手机验证码登录


    @ApiOperation(value = "查看入驻圈子")
    @GetMapping("/select/{id}")
    public Result selectEnter(@PathVariable Integer id) {
        AppletUser byId = appletUserService.getById(id);
        Integer enter = byId.getEnter();
        if (enter == 0) {
            return Result.ok().message("未入驻");
        } else if (enter == 1) {
            List<Posted> list = postedService.list();
            return Result.ok(list);
        }
        return Result.fail().message("对象为空");
    }

    @ApiOperation(value = "查看用户信息")
    @GetMapping("/selectAppletUser")
    public Result<AppletUser> selectAppletUser() {
        String s = AuthContextUtil.get();
        AppletUser byId = appletUserService.getById(Integer.valueOf(s));
        return Result.ok(byId);
    }


    @ApiOperation(value = "修改用户信息广告状态")
    @PostMapping("/updateAppletUserStart/{uid}/{start}")
    public Result<AppletUser> updateAppletUserStart(@PathVariable Integer uid, @PathVariable Integer start) {

//            LambdaQueryWrapper<AppletUser> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(AppletUser::getId,uid);

        AppletUser byId1 = appletUserService.getById(uid);
        byId1.setStart(start);
        boolean byId = appletUserService.updateById(byId1);
        if (byId) {
            return Result.ok(byId1);
        }

        return Result.fail(byId1).message("修改失败！！！");
    }


    @ApiOperation(value = "删除用户")
    @PostMapping("delectAppletUser")
    public Result delectIpaEnter(@RequestBody AppletUser appletUser) {
//        String s = AuthContextUtil.get();
        boolean b = ipaEnterService.removeById(appletUser.getId());

        if (b) {
            return Result.ok().message("删除成功");
        }
        return Result.fail().message("删除失败");
    }

    @ApiOperation(value = "导出")
    @PostMapping("/excel")
    @JsonIgnoreProperties({"customPalette"})
    public Result downloadExcel(HttpServletResponse response) {

        //创建HSSFWorkBook对象,excel的文档对象
//            HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        //excel表单
        Sheet sheet = workbook.createSheet("用户注册统计");
        //获取数据库数据
        List<AppletUser> list = appletUserService.list();

        if (list.isEmpty()) {
            list = new ArrayList<>();
        }

        //设置要导出的文件名
        String fileName = "D:/file/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM-ddHHmmss")) + "用户注册统计.xls";
        //新增数据行，并且设置单元格格式
        int rowNum = 1;
        //, "修改时间"
        String[] headers = {"ID", "昵称", "手机号", "注册时间"};


        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
                HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
                cell.setCellValue(textString);
//            cell.setCellValue(headers[i]);
        }
        for (AppletUser appletUser : list) {

            String[] rowData = new String[rowNum];
            Row sheetRow = sheet.createRow(rowNum+1);
            sheetRow.createCell(0).setCellValue(rowNum);
            sheetRow.createCell(1).setCellValue(appletUser.getNickName());
            sheetRow.createCell(2).setCellValue(((appletUser.getPhone() == null) || appletUser.getPhone().isEmpty()) ? appletUser.getPhone() : "用户暂未上传");
            sheetRow.createCell(3).setCellValue(appletUser.getCreateTime().toString());
//                sheetRow.createCell(4).setCellValue(appletUser.getUpdateTime().toString());

//            for (int colIndex = 0; colIndex < sheetRow.getRowNum(); colIndex++) {
//                Cell cell = sheetRow.createCell(colIndex);
//                cell.setCellValue();
//            }
//            rowNum++;
        }

        // 填充数据
//        for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) {
//
//            String[] rowData = list.get(rowIndex);
//            Row dataRow = sheet.createRow(rowIndex + 1);
//            for (int colIndex = 0; colIndex < rowData.length; colIndex++) {
//                Cell cell = dataRow.createCell(colIndex);
//                cell.setCellValue(rowData[colIndex]);
//            }
//        }

//            Map<String, Object> jsonData = new HashMap<>();
//
//            for (int i = 0; i < headers.length; i++) {
//                Cell cell = row.createCell(i);
//
//                for (AppletUser appletUser : list) {
//                    Row sheetRow = sheet.createRow(rowNum);
//                    if (i==0){
//                        HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
//                        cell.setCellValue(textString);
//                        sheetRow.createCell(0).setCellValue(rowNum);
//
//                        jsonData.put(textString.getString(),rowNum);
//                    }else if (i==1){
//                        HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
//                        cell.setCellValue(textString);
//                        sheetRow.createCell(1).setCellValue(appletUser.getNickName());
//                        jsonData.put(textString.getString(),appletUser.getNickName());
//                    }else if (i==2){
//                        HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
//                        cell.setCellValue(textString);
//                        sheetRow.createCell(2).setCellValue(((appletUser.getPhone() == null) || appletUser.getPhone().isEmpty()) ? appletUser.getPhone() : "用户暂未上传");
//                        jsonData.put(textString.getString(),((appletUser.getPhone() == null) || appletUser.getPhone().isEmpty()) ? appletUser.getPhone() : "用户暂未上传");
//                    }else if (i==3){
//                        HSSFRichTextString textString = new HSSFRichTextString(headers[i]);
//                        cell.setCellValue(textString);
//                        sheetRow.createCell(3).setCellValue(appletUser.getCreateTime().toString());
//                        jsonData.put(textString.getString(),appletUser.getCreateTime().toString());
//                    }
//
////                sheetRow.createCell(4).setCellValue(appletUser.getUpdateTime().toString());
//                    rowNum++;
//                }
//            }

//            ObjectMapper mapper = new ObjectMapper();
//            String json = mapper.writeValueAsString(jsonData);
        try (FileOutputStream file = new FileOutputStream(fileName)) {

            workbook.write(file);
            workbook.close();
            return Result.ok(file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 清理资源
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.fail("Excel文件导出失败！");
    }
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "excel导出")
    @PostMapping("/downexcel")
    @JsonIgnoreProperties({"customPalette"})
    public void downexcel(HttpServletResponse response) throws IOException{

        List<PromptInformationDown> list = new ArrayList<>();
        //Mybatis Plus自带的list方法，获取所有数据封装到实体类中返回实体类的列表

        //获取数据库数据
        List<AppletUser> list1 = appletUserService.list();
        if (list1.isEmpty()) {
            list1 = new ArrayList<>();
        }

        //通过循环将所得到的数据封装到PromptInformationDown 中
//        Long num = Long.valueOf(0);

//        list1.stream().forEach(a -> {
        for (int i = 0; i < list1.size(); i++) {
            PromptInformationDown d = new PromptInformationDown();
            d.setId(Long.valueOf(i+1));
            d.setNickName(list1.get(i).getNickName());
            d.setPhone(list1.get(i).getPhone());
            d.setCreateTime(list1.get(i).getCreateTime());
            //将装好的实体类添加进总list中
            list.add(d);
        }



        // 设置文本内省
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头
        //设置要导出的文件名
        String fileName = "D:/file/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM-ddHHmmss")) + "用户注册统计.xls";
//        response.setHeader("Content-disposition", "attachment;filename="+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM-ddHHmmss")) + "用户注册统计.xls");
        response.setHeader("Content-disposition", "attachment;filename="+fileName);
        EasyExcel.write(response.getOutputStream(), PromptInformationDown.class)
                .sheet("消息列表").doWrite(list);



//        //创建一个工作簿，也就是Excel文件
//        HSSFWorkbook wb = new HSSFWorkbook();
//        //创建一个工作表
//        HSSFSheet sheet = wb.createSheet("用户注册统计");
//        //获取数据库数据
//        List<AppletUser> list = appletUserService.list();
//
//        if (list.isEmpty()) {
//            list = new ArrayList<>();
//        }
//
//        //第一行，标题
//        HSSFRow row0 = sheet.createRow(0);
////        HSSFCell cell0 = row0.createCell(0);
//
//        //设置要导出的文件名
//        String fileName = "D:/file/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM-ddHHmmss")) + "用户注册统计.xls";
//        //新增数据行，并且设置单元格格式
////        cell0.setCellValue(object.get(0).getCheckName() + "签到统计表");
//        //第二行，表头
//        HSSFRow row1 = sheet.createRow(0);
////        String[] headers = {"ID", "昵称", "手机号", "注册时间"};
//        row1.createCell(0).setCellValue("ID");
//        row1.createCell(1).setCellValue("昵称");
//        row1.createCell(2).setCellValue("手机号");
//        row1.createCell(3).setCellValue("注册时间");
//        //表中数据
//        int rowInt = 1;
//        for (AppletUser appletUser : list) {
//            HSSFRow row = sheet.createRow(rowInt++);
//            int cellInt = 0;
////            row.createCell(cellInt++).setCellValue(obj.getName());
////            row.createCell(cellInt++).setCellValue(obj.getNumber());
////            row.createCell(cellInt).setCellValue(sdf.format(obj.getCheckTime()));//将日期转换成字符串，要不然存的是一个时间戳
//
//            row.createCell(0).setCellValue(rowInt);
//            row.createCell(1).setCellValue(appletUser.getNickName());
//            row.createCell(2).setCellValue(((appletUser.getPhone() == null) || appletUser.getPhone().isEmpty()) ? appletUser.getPhone() : "用户暂未上传");
////            row.createCell(3).setCellValue(sdf.format(appletUser.getCreateTime()));
//            row.createCell(3).setCellValue(appletUser.getCreateTime());
//        }
//        try {
//            //输出文件
//            //创建字节输出流
////            File file = new File("D://excel.xls");
//            FileOutputStream fos = new FileOutputStream(fileName);
//            wb.write(fos);
//            fos.flush();
//            fos.close();
//
//            return Result.ok(fos);
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.out.println("ToExcel.getExcel");
//            System.out.println("IO出异常了");
//        } finally {
//            // 清理资源
//            try {
//                wb.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return Result.fail("Excel文件导出失败！");


    }

}